package com.example.storm.music02;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class Music02 extends Service {
    private int progress=0;
    private boolean isPaused=false;
    public Music02() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int action = intent.getIntExtra("action",-1);
        switch (action){
            case 1:
                play();
                break;
            case 2:
                pause();
                break;
            case 3:
                resume();
                break;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }
    public class MyBinder extends Binder{
        public int getProgress(){
            return progress;
        }
    }

    public void play(){
        new Thread(){
            @Override
            public void run() {
                synchronized (Music02.this) {

                    for (int i = 0; i <= 800; i++) {
                        if(isPaused){
                            try {
                                Music02.this.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        progress++;
                    }
                }
            }
        }.start();
    }

    public void pause(){
        isPaused = true;

    }

    public synchronized void resume(){
        isPaused = false;
        notify();
    }
}
